package com.itheima.countroller;

import com.itheima.cammon.CommonResult;
import com.itheima.cammon.PageInof;
import com.itheima.pojo.Dish;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 王同学
 */
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    DishService dishService;

    //新增菜品
    @PostMapping
    public CommonResult add(@RequestBody Dish dish) {
        boolean res = dishService.add(dish);
        if (!res) {
            CommonResult.error("添加菜品失败");
        }
        return CommonResult.success(res);
    }
        //分页查询
    @GetMapping("/page")             //Request Param请求参数也就是设置默认值，当没有参数传进来的时候提供的一个默认值
    public CommonResult findpage(String name,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "10") Integer pageSize, Integer type) {
        //分页查询
        PageInof<Dish> res = dishService.page(name, page, pageSize, type);
        return CommonResult.success(res);
    }
    //根据id删除菜品
    @DeleteMapping
    public CommonResult delete(@RequestParam String ids) {
        //因为传进来的字符串有用逗号隔开， 所以可以用固定的格式给他转换成数组
        boolean res = dishService.delete(ids);
        if (!res) {
            return CommonResult.error("删除失败~！");
        }
        return CommonResult.success("删除成功~！");
    }

    //修改菜品
    @PutMapping
    public CommonResult update(@RequestBody Dish dish) {
        boolean res = dishService.update(dish);
        if (!res) {
            return CommonResult.error("修改失败~！");
        }
        return CommonResult.success("修改成功~！");
    }

    //设置起售和禁售
    @PostMapping("/status")
    public CommonResult status(int status, String id) {

        boolean sta = dishService.updatestatus(id,status);
        if (!sta) {
            return CommonResult.error("修改失败");
        }
        return CommonResult.success("修改成功~！");
    }
    //根据id查询菜品
    @GetMapping("/{id}")
    public CommonResult findById(@PathVariable("id") String id){
         if (id==null||id==""){
             throw new RuntimeException("要查询的id数据丢失");
         }
        Dish res = dishService.findById(id);
        return CommonResult.success(res);
    }

    //菜品下拉列表
    @GetMapping("list")
    public CommonResult findAll(String categoryId){

        return CommonResult.success(dishService.findAll(categoryId));
    }



}





